package main;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import constants.Numbers;

public class Server {
	
	public static ArrayList<MessageThread> mThreads = new ArrayList<MessageThread>();
	
	public static void main(String[] args){
	    startServer(Numbers.CONNECTION_PORT_ALIVE);
	    startServer(Numbers.CONNECTION_PORT);
	    startServerForPHP(Numbers.CONNECTION_PORT_PHP);
	}
	
	public static void log(String log)
	{
		System.out.println("[" + getCurrentTimeStamp() + "] " + log);
	}
	
	public static String getCurrentTimeStamp() {
	    SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
	    Date now = new Date();
	    String strDate = sdfDate.format(now);
	    return strDate;
	}
	
	public static void startServer(final int port)
	{
		log("Starting Server at port " + port + " ...");
		
		try {
    		log("Server: " + port + " Initialized Successfully");
	        log("Server: " + port + " Started Successfully");
	        log("Server: " + port + " waiting for client");
	        
	        new Thread(){
	        	ServerSocket serverSocket = new ServerSocket(port);
    			
	        	public void run() {
	        		try {
	        			while (true){
	        				new ServerThreadStarter(serverSocket.accept(), port).start();
	        			}
					} catch (IOException e) {
						e.printStackTrace();
					}
	        	}
	        }.start();
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	
	}
	
	private static void startServerForPHP(final int port) {
		log("Starting PHPServer at port " + port + " ...");
		
		try {
    		log("PHPServer: " + port + " Initialized Successfully");
	        log("PHPServer: " + port + " Started Successfully");
	        log("PHPServer: " + port + " waiting for client");
	        
	        new Thread(){
	        	ServerSocket serverSocket = new ServerSocket(port);
    			
	        	public void run() {
	        		try {
	        			while (true){
	        				new PHPServerThreadStarter(serverSocket.accept(), port).start();
	        			}
					} catch (IOException e) {
						e.printStackTrace();
					}
	        	}
	        }.start();
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
